#include "Job.h"
#include "Tcp.h"
#include "EventConnection.h"
#include "Thread.h"
#include <iostream>
#include <unistd.h>
#include <cstdlib>
#include <stdint.h>
#include "util.h"

using namespace std;

namespace PFS
{
    void deal_with_connection(EventConnection * conn)
    {
        char* buff[512];
        uint64_t len;
        Tcp* tcp = conn->get_tcp();
        tcp->Recv(&len,sizeof(len));
        len = ntohl(len);
        tcp->Recv(buff, len);
        cout<<"Recv "<<len<<" Bytes; Content:"<<buff<<endl;
    }
    void event_handler(const int fd, const short which, void* arg)
    {
        EventConnection *conn = (EventConnection*) arg;
        return_if_fail(conn != NULL);

        deal_with_connection(conn);
        return;
    }
    
    void EventTask::run(void* data)
    {
        EventConnection *conn = ((struct event_arg *)data)->data;
        event_set(conn->get_event(), conn->get_fd(), EV_READ | EV_PERSIST, event_handler, (void *)conn);
        event_base_set(conn->get_thread()->get_event_base(), conn->get_event());
        event_add(conn->get_event(), 0);
    }
}
